package gewu.suleju.controller;
import gewu.suleju.dao.iml.IHouseCollectionDao;
import gewu.suleju.model.pojo.HouseCollection;
import gewu.suleju.model.vo.Result;
import gewu.suleju.sevice.imp.HouseCollectionServiceImp;
import gewu.suleju.util.JWTUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@RestController
@RequestMapping("collect")
public class HouseCollectionController {
    @Autowired
    private HouseCollectionServiceImp houseCollectionServiceImp;
    @Autowired
    private IHouseCollectionDao iHouseCollectionDao;
    @RequestMapping("house")
    public Result house(String houseId , HttpServletRequest request){
        int hid = Integer.parseInt(houseId);//房子id

        String token = request.getHeader("token");
        if(token.equals("null")){
            return  new Result("501","还没有登录");
        }
        else{
            Claims claims = JWTUtil.checkJWT(token);
            int userId = (int)claims.get("id");
            boolean hcs = houseCollectionServiceImp.findUserIdAndHouseId(userId,hid);
            if(hcs){//不存在了
                HouseCollection houseCollection = new HouseCollection();
                houseCollection.setUserId(userId);
                houseCollection.setHouseInforId(hid);
                houseCollection.setCollectionDate(new Date());
                iHouseCollectionDao.save(houseCollection);
                return new Result("200","收藏成功");
            }
            else {//已经存在了，进行删除
                houseCollectionServiceImp.deleteCollection(userId,hid);
                return new Result("500","已经收藏过了");
            }
        }

    }

    @RequestMapping("have")
    public Result have(String houseId , HttpServletRequest request){
        int hid = Integer.parseInt(houseId);//房子id

        String token = request.getHeader("token");
        if(token.equals("null")){
            return  new Result("501","还没有登录");
        }
        Claims claims = JWTUtil.checkJWT(token);
        int userId = (int)claims.get("id");
        boolean hcs = houseCollectionServiceImp.findUserIdAndHouseId(userId,hid);
        if(!hcs){//存在
            return new Result("200","已经收藏过了");
        }
        else{
            return new Result("500","没有收藏");
        }
    }

}
